package cn.lyf.myblog.controller.api;

import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.node.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import cn.lyf.myblog.mybatis.entity.*;
import static cn.lyf.myblog.controller.api.JsonUtils.*;
import javax.mail.MessagingException;

import cn.lyf.myblog.mybatis.mappers.*;
import java.util.*;

@RestController
public class Power {
    @Autowired
    UserMapper userMapper;

    @Autowired
    UserInfoMapper userInfoMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    EmailUtils emailuUtils;

    @Transactional(rollbackFor = Exception.class)
    public boolean register(String json) throws Exception {
        User user = mapper.readValue(json, User.class);
        ObjectNode res = mapper.createObjectNode();
        res.put("success", false);
        userMapper.insertUser(user);
        userRoleMapper.insertUserRole(user.getUid(), 3);
        UserInfo userInfo = mapper.readValue(json, UserInfo.class);
        userInfo.setUid(user.getUid());
        int r = userInfoMapper.insertUserInfo(userInfo);
        if (r > 0) {
            return true;
        }
        return false;
    }

    @PostMapping("/send")
    public JsonNode sendCode(@RequestBody JsonNode json) throws Exception {
        ObjectNode res = mapper.createObjectNode();
        try {
            emailuUtils.sendEmail(getString(json, "/email"));
            res.put("success", true);
            res.put("code", 200);
            res.put("message", "发送验证码成功！");
        } catch (MailException e1) {
            res.put("success", false);
            res.put("code", 471);
            res.put("message", e1.getMessage());
        } catch (MessagingException e2) {
            res.put("success", false);
            res.put("code", 472);
            res.put("message", e2.getMessage());
        }
        return res;
    }

    @PostMapping("/check")
    public String verCode(@RequestParam Map<String, Object> map, Model model) throws Exception {
        ObjectNode json = mapper.convertValue(map, ObjectNode.class);
        boolean b = emailuUtils.verification(getString(json, "/email"), getString(json, "/vercode"));
        if (b && register(json.toString())) {
            model.addAttribute("msg", "注册成功");
            return "/toLogin";
        }
        model.addAttribute("msg", "注册失败");
        return "/register";
    }
}
